﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using log4net;

namespace HydroDesktop.Search
{
    public class WebServicesList
    {
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);


        private readonly string SERVICES_XML_NAME = Properties.Settings.Default.WebServicesFileName;
        private IHISCentralSearcher _searcher;
        private static TimeSpan _UpdatePeriod = new TimeSpan(0, HydroDesktop.Search.Properties.Settings.Default.WebServiceListUpdateInMinutes, 0);

        public WebServicesList()
        {
            WebServicesFilename = Path.Combine(ServicesXmlDirectoryPath, SERVICES_XML_NAME);

        }

        /// <summary>
        /// Time Period between updates
        /// </summary>
        public static TimeSpan UpdateTime { get { return _UpdatePeriod; } set { _UpdatePeriod = value; } }
        public static DateTime LastUpdated { get; set; }
        public static string WebServicesFilename { get; set; }

        /// <summary>
        ///  Expect that this will be a method in the main class someday
        /// </summary>
        private static string ServicesXmlDirectoryPath
        {
            get
            {
                var servicesXMLPath = HydroDesktop.Configuration.Settings.Instance.ApplicationDataDirectory;
                return servicesXMLPath;
            }
        }

        //gets the 'WebServices' xml file from HIS Central
        public XmlDocument GetWebServicesList()
        {
            var centralList = HydroDesktop.Configuration.Settings.Instance.HISCentralURLList;

            if (File.Exists(WebServicesFilename))
            {
                //Should be longer rather than shorter that is not necessary to update the xml file
                if (LastUpdated.Add(UpdateTime) > DateTime.Now)
                {
                    try
                    {
                        return ReadFile(WebServicesFilename);
                    }

                    catch
                    {
                          // we cant read it. it exists
                         XmlDocument servList = GetWebServicesFromHISCentral(centralList);

                         try
                         {
                             SaveFile(WebServicesFilename, servList);
                         } 
                     
                         catch
                         {
                             log.Error("Could not write WebServices.xml");
                         }

                         return servList;
                    }
                }

            }

            {
                return GetWebServicesFromHISCentral(centralList);
            }

        }
        public void SaveFile(string webServicesFilename, XmlDocument servList)
        {
            
            if (String.IsNullOrEmpty(webServicesFilename))
            {
                throw new FileNotFoundException("Webservices file not found");
            }
          var outputFile =  File.Create(webServicesFilename);
            var writer = XmlWriter.Create(outputFile);
            servList.WriteContentTo(writer);
           
        }

        public XmlDocument ReadFile(string webServicesFilename)
        {
            if (String.IsNullOrEmpty(webServicesFilename))
            {
                throw new FileNotFoundException("Webservices file not found");
            }
            XmlDocument getWebServ = new XmlDocument();
            getWebServ.Load(webServicesFilename);
            return getWebServ;
        }

        //gets the 'WebServices' xml file from HIS Central
        private XmlDocument GetWebServicesFromHISCentral(IList<string> hisCentralUrl)
        {
            foreach (var url in hisCentralUrl)
            {
                try
                {
                    _searcher = _searcher ?? new HISCentralSearcher(url);
                    RefreshListFromHisCentral(_searcher);
                    var document = new XmlDocument();
                    try
                    {

                        document.Load(WebServicesFilename);
                    }
                    catch (FileNotFoundException ex)
                    {
                        log.Error("HIS central GetWebServices Fail to write a file" + url);
                    }
                    return document;
                }
                catch
                {
                    log.Error("HIS central GetWebServices Failed " + url);
                    continue;
                }
            }
            throw new HydrodesktopSearchException("All HIS Central GetWebServices Failed");

            // wrong logic here... searcher method saves afile
            //try
            //{
            //    document.Save(WebServicesFilename);
            //}
            //catch
            //{
            //    log.Error("Cannot write file '" + WebServicesFilename + "' not fatal");
            //});


        }

        public void RefreshListFromHisCentral(IHISCentralSearcher searcher)
        {
            searcher.GetWebServicesXml(WebServicesFilename);
        }

        #region mock
        public WebServicesList(String fileName, IHISCentralSearcher searcher)
        {

            WebServicesFilename = fileName;
            _searcher = searcher;
        }

        #endregion

    }
}
